package com.solution.wx.product.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.home.service.SiteConfigItemService;
import com.solution.admin.product.entity.ProductBrandEntity;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.service.ProductBrandService;
import com.solution.admin.product.service.ProductCategoryPropertyFilterService;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductImageService;
import com.solution.admin.product.service.ProductPriceService;
import com.solution.admin.product.service.ProductPropertyRelaService;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.promotion.service.PromotionProductService;
import com.solution.admin.promotion.service.PromotionService;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.common.constants.PublicConstants;

/**
 * 微信端报价单查询
 * @author llp
 */
@RequestMapping("/wx/product/price")
@Controller("wxProductPriceController")
public class ProductPriceSearchController extends BaseController {
	
	@Autowired
	private ProductBrandService productBrandService;
	
	@Autowired
	private ProductCategoryPropertyFilterService productCategoryPropertyFilterService;

	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductPriceService productPriceService;
	
	@Autowired
	private ProductPropertyRelaService productPropertyRelaService;
	
	@Autowired
	private ProductImageService productImageService;
	
	@Autowired
	private SiteConfigItemService siteConfigItemService;
	
	@Autowired
	private PromotionProductService promotionProductService;
	
	@Autowired
	private PromotionService promotionService;
	
	/**
	 * 微信商品报价单查询
	 * 筛选项查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/search")
	public String listProductListPage(HttpServletRequest request, HttpServletResponse response) {
		// 请求参数回现到页面用的于第二次查询
//		Map<String, String> hiddenParamMap = new HashMap<String, String>();
		// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
		String requestType = request.getParameter("requestType");

		request.setAttribute(PublicConstants.CURRENT_PAGE_KEY, PublicConstants.PAGE_QUOTE);

		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 页面参数
		// 商品分类
		String categoryIds = request.getParameter("categoryId");
		// 品牌
		String brandIds = request.getParameter("brandIds");
		request.setAttribute("categoryIds", categoryIds);
		request.setAttribute("brandIds", brandIds);
		// 搜索关键字（根据商品分类查询）
		String productSearchKey = request.getParameter("searchKey");
		// 排序
		String sortField = request.getParameter("sortField");
		if (StringUtil.isEmpty(sortField)) {
			sortField = "SORT_NO";
		}
		String sortType = request.getParameter("sortType");
		if (StringUtil.isEmpty(sortType)) {
			sortType = " ASC ";
		}
		// 用于界面回显参数
		Map<String, Object> requestParamMap = new HashMap<String, Object>();
		try {
			// 【1】、查询所有商品类型
			List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
			if (topCategoryList != null && topCategoryList.size() > 0) {
				for (ProductCategoryEntity category : topCategoryList) {
					if (StringUtil.isNotEmpty(category.getSubCategoryListStr())) {
						List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("[" + category.getSubCategoryListStr() + "]",
						        ProductCategoryEntity.class);
						category.setSubCategoryList(tmpCategoryList);
						category.setSubCategoryListStr("[" + category.getSubCategoryListStr() + "]");
					}
				}
			}
			request.setAttribute("topCategoryList", topCategoryList);
			// 品牌列表
			List<ProductBrandEntity> brandList = null;
			// 就是需要所有的品牌
			param.put("categoryIds", null);
			// 搜索categoryIds 上绑定的所有相关品牌
			brandList = productBrandService.listAllBrandForWXIndex(param);
			request.setAttribute("brandList", brandList);

			// 还需要所有商品分类
			// 查询指定分类的所有子级分类
			List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
			request.setAttribute("categoryList", categoryList);

			// key-value = brand_id-brand_name 方面页面显示品牌名称
			Map<Long, String> brandNameMap = new HashMap<Long, String>();
			if (brandList != null && brandList.size() > 0) {
				for (ProductBrandEntity brand : brandList) {
					if (StringUtil.isNotEmpty(brand.getSubBrandListStr())) {
						List<ProductBrandEntity> subBrandList = JSONArray
						        .parseArray("[" + brand.getSubBrandListStr() + "]", ProductBrandEntity.class);
						brand.setSubBrandList(subBrandList);
						brand.setSubBrandListStr("[" + brand.getSubBrandListStr() + "]");
					}
					brandNameMap.put(brand.getId(), brand.getBrandNameCh());
				}
				request.setAttribute("defaultSubBrandList", brandList.get(0).getSubBrandList());
			}
			
			/**
			 * 检索商品
			 * */
			param.put("sortField", sortField);
			param.put("sortType", sortType);

			// 品牌
			if (StringUtil.isNotEmpty(brandIds)) {
				param.put("brandIds", "(" + brandIds + ")");
				// 添加筛选条件
				for (String brandIdStr : brandIds.split(",")) {
					requestParamMap.put(brandIdStr, "1");
				}
			}
			// 商品分类
			if (StringUtil.isNotEmpty(categoryIds)) {
				param.put("categoryIds", "(" + categoryIds + ")");
				// 添加筛选条件
				for (String categoryIdStr : categoryIds.split(",")) {
					requestParamMap.put(categoryIdStr, "1");
				}
			}
			
			String pageNumStr = request.getParameter("pageNum");
			if (StringUtil.isEmpty(pageNumStr)) {
				pageNumStr = "1";
			}
			int pageNum = Integer.parseInt(pageNumStr);
			int numPerPage = 8;
			PageParam pageParam = super.getPageParam(request);
			pageParam.setPageNum(pageNum);
			pageParam.setNumPerPage(numPerPage);
			//搜索的关键字
			param.put("searchKey", productSearchKey);
			param.put("customerLevel", getCustomerLevel());
			param.put("isLogin", isLogin(request)? "1" : "0");
			param.put("customerId", getCustomerId());
			PageBean pageBean = productService.listProductPageForIndex(pageParam, param);

			// 如果是异步，直接写response
			if ("sync".equals(requestType)) {
				try {
					response.getWriter().write(JSONObject.toJSON(pageBean).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("productList", pageBean.getRecordList());
			request.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("searchKey", productSearchKey);
		request.setAttribute("requestParamMap", requestParamMap);
		request.setAttribute("sortField", sortField);
		request.setAttribute("sortType", sortType);
		request.setAttribute("prevBtn", StringUtil.isEmpty(request.getParameter("prevBtn")) ? "defaultbtn" : request.getParameter("prevBtn"));
		String pageType = request.getParameter("pageType");
		if (null == pageType) {
			pageType = "default";
		}
		request.setAttribute("pageType", pageType);
		return "wx/product/product_price_list";
	}
}
